import React, { useState, useEffect, useMemo } from 'react';
import { Tabs, Button, message, Space, Popconfirm, Tooltip } from 'antd';
import { EditOutlined, DeleteOutlined, SyncOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { ConnectionInfo } from '@/types/nl2sql/type';
import { Search } from '@/components/eai-design';
import { Empty } from '@/components/eai-design';
import nl2sqlService from '@/api/services/nl2sqlService';
import TerminologyManagement from './terminology-management';
import CaseManagement from './case-management';
import QuerySettings from './query-settings';
import TableManagementModal from './table-management-modal';
import Tables from '@/components/tables/tables';
import dayjs from 'dayjs';


interface ConnectDetailProps {
  connections: ConnectionInfo[];
  selectedConnection?: ConnectionInfo | null;
  onConnectionSelect?: (connection: ConnectionInfo) => void;
  onRefresh?: () => void;
}

const ConnectDetail: React.FC<ConnectDetailProps> = ({
  connections,
  selectedConnection,
  onConnectionSelect,
  onRefresh,
}) => {
  const [activeTab, setActiveTab] = useState('dataTable');
  const [searchValue, setSearchValue] = useState('');
  const [tableManagementModalVisible, setTableManagementModalVisible] = useState(false);
  const [selectedTableInfo, setSelectedTableInfo] = useState<{
    table_data_id: string;
    table_name: string;
  } | null>(null);
  
  // 分页状态管理
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 删除表的请求
  const { runAsync: deleteTableRequest, loading: deleteTableLoading } = useRequest(
    async (datasetId: string, tableId: string) => {
      return await nl2sqlService.deleteTable(datasetId, tableId);
    },
    {
      manual: true,
      onSuccess: (result) => {
        message.success('删除表成功');
      },
      onError: (error) => {
        console.error('删除表失败:', error);
      },
    }
  );


  useEffect(() => {
    setCurrentPage(1);
    setPageSize(10);
  }, [selectedConnection?.database_id]);

  // 分页处理函数
  const handlePaginationChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  // 过滤表格数据
  const filteredTableInfos = selectedConnection?.table_simple_infos?.filter((table) => {
    if (!searchValue) return true;
    return table.table_name.toLowerCase().includes(searchValue.toLowerCase());
  }) || [];

  // 计算分页后的数据（如果分页后无数据且当前页不为1，则自动跳转到上一页）useMemo实现
  const paginatedTableInfos = useMemo(() => {
    const startIdx = (currentPage - 1) * pageSize;
    const endIdx = currentPage * pageSize;
    const pageData = filteredTableInfos.slice(startIdx, endIdx);
    // 如果当前页无数据且不是第一页，自动跳转到上一页
    if (pageData.length === 0 && currentPage > 1) {
      setCurrentPage(currentPage - 1);
      return filteredTableInfos.slice((currentPage - 2) * pageSize, (currentPage - 1) * pageSize);
    }
    return pageData;
  }, [filteredTableInfos, currentPage, pageSize]);

  // 表格列定义
  const columns = [
    {
      title: '数据表名称',
      dataIndex: 'table_name',
      key: 'table_name',
      width: 200,
      render: (text: string) => (
        <span className="text-blue-600 font-medium">{text}</span>
      ),
    },
    {
      title: '最新同步时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (text: string) => {
        return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: any) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleManage(record)}
            className="text-blue-600 hover:text-blue-800"
          >
            管理
          </Button>
          <Popconfirm
            title="删除后可能会影响对该数据表的理解,是否确认删除?"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              size="small"
              icon={<DeleteOutlined />}
              className="text-red-600 hover:text-red-800"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理管理按钮
  const handleManage = (record: any) => {
    setSelectedTableInfo({
      table_data_id: record.table_data_id,
      table_name: record.table_name,
    });
    setTableManagementModalVisible(true);
  };

  // 处理删除按钮
  const handleDelete = async (record: any) => {
    if (!selectedConnection?.schema_dataset) {
      message.error('无法获取数据集ID');
      return;
    }

    try {
      await deleteTableRequest(selectedConnection.schema_dataset, record.table_data_id);
      // 删除成功后刷新数据
      onRefresh?.();
    } catch (error) {
      // 错误已经在 useRequest 的 onError 中处理了
      console.error('删除表时发生错误:', error);
    }
  };

  // 处理同步按钮
  const handleSync = () => {
    console.log('TODO: 同步数据表');
    message.info('同步功能待实现');
  };

  // 处理添加按钮
  const handleAdd = () => {
    console.log('TODO: 添加数据表');
    message.info('添加功能待实现');
  };

  // 处理弹窗关闭
  const handleTableManagementModalClose = () => {
    setTableManagementModalVisible(false);
    setSelectedTableInfo(null);
  };

  // // 如果没有选中的连接，显示空状态
  // if (!selectedConnection) {
  //   return (
  //     <div className="flex h-full items-center justify-center">
  //       <div className="text-center">
  //         <div className="text-gray-500 mb-4">请选择一个数据库连接</div>
  //       </div>
  //     </div>
  //   );
  // }

  return (
    <div className="flex h-full flex-col p-2 nl2sql-connect-detail">

      {connections.length === 0 && <Empty fontText="暂无信息，请先创建数据库" />}

      {/* 标签页导航 */}
      {connections.length > 0 &&
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          className="flex-1 flex flex-col"
          items={[
            {
              key: 'dataTable',
              label: '数据表管理',
              children: (
                <div className="flex-1 flex flex-col p-4 h-full">
                  {/* 搜索栏 */}
                  <div className="mb-4">
                    <Search
                      placeholder="搜索"
                      className="w-full max-w-sm"
                      allowClear
                      value={searchValue}
                      onChange={(e) => {
                        setSearchValue(e.target.value);
                        // 搜索时重置分页状态
                        setCurrentPage(1);
                      }}
                    />
                  </div>

                  {/* 数据表列表 */}
                  <div className="flex-1 overflow-hidden">
                    <Tables
                      columns={columns}
                      dataSource={paginatedTableInfos}
                      rowKey="table_data_id"
                      paginationProps={{
                        total: filteredTableInfos.length,
                        current: currentPage,
                        pageSize: pageSize,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        // pageSizeOptions: [10, 20, 50],
                        onChange: handlePaginationChange,
                      }}
                      locale={{
                        emptyText: (
                          <Empty fontText="暂无数据表" />
                        ),
                      }}
                    />
                  </div>
                </div>
              ),
            },
            // {
            //   key: 'terminology',
            //   label: (
            //     <span>
            //       术语管理
            //       <Tooltip title={"为了帮助模型更好的理解您在问数过程中的目标表述，您可以将常见表述中涉及到的专有术语、指标计算口径等信息在此录入。"}>
            //         <QuestionCircleOutlined className="ml-1 text-[#86909C]" />
            //       </Tooltip>
            //     </span>
            //   ),
            //   children: (
            //     <div className="flex-1">
            //       <TerminologyManagement knowledgeId={selectedConnection?.knowledge_dataset || ''} />
            //     </div>
            //   ),
            // },
            {
              key: 'case',
              label: (
                <span>
                  案例管理
                  <Tooltip title={"您可以通过添加案例来提升模型解决此类问题的准确率。一条案例包含一个问题的问法描述与其预期正确执行的完整SQL内容。"}>
                    <QuestionCircleOutlined className="ml-1 text-[#86909C]" />
                  </Tooltip>
                </span>
              ),
              children: (
                <div className="flex-1 h-full">
                  <CaseManagement knowledgeId={selectedConnection?.sql_dataset || ''} />
                </div>
              ),
            },
            {
              key: 'query',
              label: '查询设置',
              children: (
                <div className="flex-1">
                  <QuerySettings selectedConnection={selectedConnection} />
                </div>
              ),
            },
          ]}
        />
      }

      {/* 数据表管理弹窗 */}
      <TableManagementModal
        visible={tableManagementModalVisible}
        onCancel={handleTableManagementModalClose}
        tableInfo={selectedTableInfo}
        connectionInfo={selectedConnection || null}
        onRefresh={onRefresh || (() => {})}
      />
    </div>
  );
};

export default ConnectDetail; 